/*
1. 在使用promise时, 需要通过new关键字去new一个promise对象,由此可见, promise其实是一个class类
2. 在执行这个类时,需要传递一个回调函数(执行器executor), 执行器会立即执行
3. promise当中有三种状态 pending fulfilled rejected 等待 成功 失败,并且状态确定后就不可改变
   pending ==> fulfilled
   pending ==> rejected
4. resolve(将状态变为fulfilled) 和 reject是用来更改状态的(将状态变为rejected)
5. 传给resolve的值就是执行成功后的值, 传给reject的值就是执行失败的原因
6.promise可以调用then方法, 在执行then中的方法时判断promise的状态, 如果状态是fulfilled,则需要调用成功回调, 如果状态是rejected,则需要调用失败回调, then方法是原型对象上的一个方法
7.then成功回调有一个参数表示成功的值, 失败回调有一个参数表示失败的原因
 */
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
  constructor (executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }
  status = PENDING
  value = undefined;
  reason = undefined;
  successCallBack = []
  failCallBack = []
  resolve = value => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    while (this.successCallBack.length) this.successCallBack.shift()()
  }
  reject = reason => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    while (this.failCallBack.length) this.failCallBack.shift()()
  }
  then (successCallBack, failCallBack) {
    successCallBack = successCallBack instanceof Function ? successCallBack : value => value
    failCallBack = failCallBack instanceof Function ? failCallBack : reason => { throw reason }
    let newPromise = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let successInfo = successCallBack(this.value)
            resolvePromise(newPromise, successInfo, resolve, reject)
          }catch (e) {
            this.reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let failInfo = failCallBack(this.reason)
            resolvePromise(newPromise, failInfo, resolve, reject)
          }catch (e) {
            this.reject(e)
          }
        }, 0)
      } else {
        if (successCallBack instanceof Function) this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let successInfo = successCallBack(this.value)
              resolvePromise(newPromise, successInfo, resolve, reject)
            }catch (e) {
              this.reject(e)
            }
          }, 0)
        })
        if (failCallBack instanceof Function) this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let failInfo = failCallBack(this.reason)
              resolvePromise(newPromise, failInfo, resolve, reject)
            }catch (e) {
              this.reject(e)
            }
          }, 0)
        })
      }
    })
    return newPromise
  }
  finally (callback) {
    if (callback instanceof Function) {
      return this.then(value => {
        return  MyPromise.resolve(callback()).then(() => value)
      }, reason => {
        return  MyPromise.resolve(callback()).then(() => {throw reason})
      })
    }
  }
  catch (failCallBack) {
    return this.then(undefined, failCallBack)
  }
  static all (array) {
    let resultArr = []
    let index = 0
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        resultArr[key] = value
        index++
        if (index === array.length) {
          resolve(resultArr)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          addData(i, current)
        }
      }
    })
  }
  static resolve (value) {
    if (value instanceof MyPromise) return value
    return new MyPromise(resolve => resolve(value))
  }
}
function resolvePromise (newPromise, c, resolve, reject) {
  if (newPromise === c) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  }
  if (c instanceof MyPromise) {
    c.then(resolve, reject)
  } else {
    resolve(c)
  }
}
module.exports = MyPromise
